from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
  """
  自定义jwt认证成功返回数据
  :param token: 本次登录成功后返回的jwt
  :param user: 本次登录成功后，从数据库查询到的用户模型信息
  :param request: 本次客户端的请求对象
  :return:
  """
  return {
    "token": token,
    "id": user.id,
    "username": user.username
  }


class MobileAuthBackend:
  """
  通过手机号码验证用户
  """

  def authenticate(self, request, username=None, password=None):
    try:
      user = User.objects.get(mobile=username)
      if user.check_password(password):
        return user
      return None
    except User.DoesNotExist:
      return None

  def get_user(self, user_id):
    try:
      return User.objects.get(pk=user_id)
    except User.DoesNotExist:
      return None
